package com.imessage.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.*;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

//用于进行Https请求的HttpClient

@Slf4j
public class HttpClientUtils {
    /**
     * 字符编码 UTF-8
     * */
    public final static String ENCODING = "UTF-8";


    private static final int TIME_OUT = 5;


    public static String sendHttpRequestGet(String url, String encoding){
        CloseableHttpClient client = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String body = "";
        try {
            //创建post方式请求对象
            HttpGet httpGet = new HttpGet(url);
            log.info("请求地址：" + url);
            //执行请求操作，并拿到结果（同步阻塞）
            response = client.execute(httpGet);
            //获取结果实体
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                //按指定编码转换结果实体为String类型
                body = EntityUtils.toString(entity, encoding);
            }
            EntityUtils.consume(entity);
        }catch (Exception e){
            log.error("sendHttpRequestPost --"+e);
        }finally {
            if(null != response){
                try {
                    //释放链接
                    response.close();
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }
        return body;
    }

    /**
     * 模拟Post请求
     * @param url       资源地址
     * @param map   参数列表
     * @param encoding  编码
     * @return
     * @throws Exception
     */
    public static String sendHttpRequestPost(String url, Map<String,String> map, String encoding)   {
        String body = "";
        //创建httpclient对象
        CloseableHttpClient client = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        try {
            //创建post方式请求对象
            HttpPost httpPost = new HttpPost(url);

            //装填参数
            List<NameValuePair> nvps = new ArrayList<NameValuePair>();
            if (map != null) {
                for (Map.Entry<String, String> entry : map.entrySet()) {
                    nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
                }
            }
            //设置参数到请求对象中
            httpPost.setEntity(new UrlEncodedFormEntity(nvps, encoding));

            log.info("请求地址：" + url);
            log.info("请求参数：" + nvps.toString());

            //设置header信息
            //指定报文头【Content-type】、【User-Agent】
            //  httpPost.setHeader("Content-type", "application/x-www-form-urlencoded");
            // httpPost.setHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");

            //执行请求操作，并拿到结果（同步阻塞）
            response = client.execute(httpPost);
            //获取结果实体
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                //按指定编码转换结果实体为String类型
                body = EntityUtils.toString(entity, encoding);
            }
            EntityUtils.consume(entity);

        }catch (Exception e){
            log.error("sendHttpRequestPost --"+e);
        }finally {
            if(null != response){
                try {
                    //释放链接
                    response.close();
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }
        log.info(body);
        return body;
    }


    /**
     * 使用HTTP POST 发送文本
     *
     * @param httpUrl
     *            发送的地址
     * @param postBody
     *            发送的内容
     * @return 返回HTTP SERVER的处理结果,如果返回null,发送失败
     */
    public static String sentPost(String httpUrl, String postBody) {
        return sentPost(httpUrl, postBody, "UTF-8", null);
    }

    /**
     * 使用HTTP POST 发送文本
     *
     * @param httpUrl
     *            发送的地址
     * @param postBody
     *            发送的内容
     * @return 返回HTTP SERVER的处理结果,如果返回null,发送失败
     */
    public static String sentPost(String httpUrl, String postBody, String encoding) {
        return sentPost(httpUrl, postBody, encoding, null);
    }

    /**
     * 使用HTTP POST 发送文本
     * @param httpUrl   目的地址
     * @param postBody  post的包体
     * @param headerMap 增加的Http头信息
     * @return
     */
    public static String sentPost(String httpUrl, String postBody, Map<String, String> headerMap) {
        return sentPost(httpUrl, postBody, "UTF-8", headerMap);
    }

    /**
     * 使用HTTP POST 发送文本
     *
     * @param httpUrl
     *            发送的地址
     * @param postBody
     *            发送的内容
     * @param encoding
     *            发送的内容的编码
     * @param headerMap 增加的Http头信息
     * @return 返回HTTP SERVER的处理结果,如果返回null,发送失败
     * .................
     */
    public static String sentPost(String httpUrl, String postBody,
                                  String encoding, Map<String, String> headerMap) {
        HttpURLConnection httpCon = null;
        String responseBody = null;
        URL url = null;
        try {
            url = new URL(httpUrl);
        } catch (MalformedURLException e1) {
            return null;
        }
        try {
            httpCon = (HttpURLConnection) url.openConnection();
        } catch (IOException e1) {
            return null;
        }
        if (httpCon == null) {
            return null;
        }
        httpCon.setDoOutput(true);
        httpCon.setConnectTimeout(TIME_OUT * 1000);
        httpCon.setReadTimeout(TIME_OUT * 1000);
        httpCon.setDoOutput(true);
        httpCon.setUseCaches(false);
        try {
            httpCon.setRequestMethod("POST");
        } catch (ProtocolException e1) {
            return null;
        }
        if (headerMap != null) {
            Iterator<Map.Entry<String, String>> iterator = headerMap.entrySet().iterator();
            while (iterator.hasNext()) {
                Map.Entry<String, String> entry = iterator.next();
                httpCon.addRequestProperty(entry.getKey(), entry.getValue());
            }
        }
        OutputStream output;
        try {
            output = httpCon.getOutputStream();
        } catch (IOException e1) {
            return null;
        }
        try {
            if(StringUtils.isNotBlank(postBody)){
                output.write(postBody.getBytes(encoding));
            }
        } catch (UnsupportedEncodingException e1) {
            return null;
        } catch (IOException e1) {
            return null;
        }
        try {
            output.flush();
            output.close();
        } catch (IOException e1) {
            return null;
        }
        // 开始读取返回的内容
        InputStream in;
        try {
            in = httpCon.getInputStream();
        } catch (IOException e1) {
            e1.printStackTrace();
            return null;
        }
        /**
         * 这个方法可以在读写操作前先得知数据流里有多少个字节可以读取。
         * 需要注意的是，如果这个方法用在从本地文件读取数据时，一般不会遇到问题，
         * 但如果是用于网络操作，就经常会遇到一些麻烦。
         * 比如，Socket通讯时，对方明明发来了1000个字节，但是自己的程序调用available()方法却只得到900，或者100，甚至是0，
         * 感觉有点莫名其妙，怎么也找不到原因。
         * 其实，这是因为网络通讯往往是间断性的，一串字节往往分几批进行发送。
         * 本地程序调用available()方法有时得到0，这可能是对方还没有响应，也可能是对方已经响应了，但是数据还没有送达本地。
         * 对方发送了1000个字节给你，也许分成3批到达，这你就要调用3次available()方法才能将数据总数全部得到。
         *
         * 经常出现size为0的情况，导致下面readCount为0使之死循环(while (readCount != -1) {xxxx})，出现死机问题
         */
        int size = 0;
        try {
            size = in.available();
        } catch (IOException e1) {
            return null;
        }
        if (size == 0) {
            size = 1024;
        }
        byte[] readByte = new byte[size];
        // 读取返回的内容
        int readCount = -1;
        try {
            readCount = in.read(readByte, 0, size);
        } catch (IOException e1) {
            return null;
        }
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        while (readCount != -1) {
            baos.write(readByte, 0, readCount);
            try {
                readCount = in.read(readByte, 0, size);
            } catch (IOException e) {
                return null;
            }
        }
        try {
            responseBody = new String(baos.toByteArray(), encoding);
        } catch (UnsupportedEncodingException e) {
            return null;
        } finally {
            if (httpCon != null) {
                httpCon.disconnect();
            }
            if (baos != null) {
                try {
                    baos.close();
                } catch (IOException e) {
                }
            }
        }
        return responseBody;
    }





    public static void main(String [] args)  {

    }


}